<?php
declare (strict_types=1);

namespace app\index\service;

use app\index\model\Order;
use app\index\model\OrderCommodity;
use think\Exception;
use think\model\Relation;

class VerificationService
{

    private $user;

    public function __construct()
    {

        $orderId = request()->param("order");
        $order = Order::whereNotIn('status', [1, 4, 6])->find($orderId);
        if (!$order)
            throw new Exception("订单状态不支持核销", HTTP_NOTACCEPT);
        global $user;
        $this->user = $user;
    }


    public function index($orderId)
    {

        $list = OrderCommodity::where(
            [
                'order_id' => $orderId,
                'type' => 2,
                'status' => [2, 4]
            ])
            ->field(['id', 'commodity_id', 'count', 'sku_id', 'status', 'type', 'store_id'])
            ->with(
                [
                    'commodity' => function (Relation $query) {
                        $query->bind(['commodity_name' => 'name', 'master']);
                    },
                    'sku' => function (Relation $query) {
                        $query->bind(['pvs_value']);
                    },
                ]
            )
            ->select();
        return [HTTP_SUCCESS, $list];
    }


    public function qrcode(array $data)
    {
        $list = OrderCommodity::where(
            [
                'type' => 2,
                'status' => 2,
                'id' => $data['ids'],
                'order_id' => $data['order'],
                'store_id' => $data['store']
            ]
        )->field('id')->select()->toArray();
        $ids = array_column($list, 'id');

        global $mid;
        $qrcodeData = [
            'mall_id' => $mid,
            'order' => $data['order'],
            'ids' => $ids,
            'user' => $this->user['id'],
            'store' => $data['store'],
        ];
        $sceneData = [
            "scene" => $data['scene'] ?? "",
            "page" => $data['page'] ?? "pages/accept/accept",
        ];
        $qrcodeService = new QrcodeService();
        list($code, $qrcode) = $qrcodeService->verification($qrcodeData, $sceneData);
        if ($code !== HTTP_SUCCESS)
            throw new Exception('二维码生成失败', HTTP_NOTACCEPT);
        $diffIds = array_values(array_diff($data['ids'], $ids));

        return [HTTP_SUCCESS, ['qrcode' => $qrcode, 'ids' => $ids, 'diffIds' => $diffIds]];

    }
}
